<template>
	<view class="order-list-container">
		<!-- 筛选栏 -->
		<view class="filter-bar">
			<picker 
				:range="statusOptions" 
				range-key="name"
				:value="statusIndex"
				@change="onStatusChange"
			>
				<view class="filter-item">
					<text>{{ statusOptions[statusIndex].name }}</text>
					<text class="arrow">▼</text>
				</view>
			</picker>
			
			<picker 
				:range="categoryOptions" 
				range-key="name"
				:value="categoryIndex"
				@change="onCategoryChange"
			>
				<view class="filter-item">
					<text>{{ categoryOptions[categoryIndex].name }}</text>
					<text class="arrow">▼</text>
				</view>
			</picker>
		</view>
		
		<!-- 订单列表 -->
		<scroll-view 
			class="order-scroll" 
			scroll-y 
			@scrolltolower="loadMore"
			refresher-enabled 
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<view class="order-item" v-for="order in orderList" :key="order.id" @click="goOrderDetail(order.id)">
				<view class="order-header">
					<text class="order-title">{{ order.title }}</text>
					<text class="order-status" :class="getStatusClass(order.status)">
						{{ getStatusText(order.status) }}
					</text>
				</view>
				
				<view class="order-content">
					<text class="order-desc">{{ order.description }}</text>
				</view>
				
				<view class="order-info">
					<view class="info-left">
						<text class="budget">￥{{ order.budget }}</text>
						<text class="category">{{ order.categoryName }}</text>
					</view>
					<view class="info-right">
						<text class="user">{{ order.userName }}</text>
						<text class="time">{{ formatTime(order.createTime) }}</text>
					</view>
				</view>
				
				<!-- 操作按钮 -->
				<view class="order-actions" v-if="showActions(order)">
					<button 
						class="action-btn accept" 
						v-if="canAccept(order)"
						@click.stop="acceptOrder(order.id)"
					>
						接单
					</button>
					
					<button 
						class="action-btn assign" 
						v-if="canAssign(order)"
						@click.stop="assignOrder(order.id)"
					>
						指派
					</button>
					
					<button 
						class="action-btn complete" 
						v-if="canComplete(order)"
						@click.stop="completeOrder(order.id)"
					>
						完成
					</button>
					
					<button 
						class="action-btn cancel" 
						v-if="canCancel(order)"
						@click.stop="cancelOrder(order.id)"
					>
						取消
					</button>
				</view>
			</view>
			
			<view class="load-more" v-if="hasMore">
				<text v-if="loading">加载中...</text>
				<text v-else>上拉加载更多</text>
			</view>
			
			<view class="no-more" v-if="!hasMore && orderList.length > 0">
				<text>没有更多数据了</text>
			</view>
			
			<view class="empty" v-if="!loading && orderList.length === 0">
				<image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">暂无订单数据</text>
				<text class="empty-subtext">快去创建您的第一个订单吧</text>
			</view>
		</scroll-view>
		
		<!-- 发布按钮 -->
		<view class="fab" v-if="$store.getters.isUser" @click="goCreateOrder">
			<text class="fab-icon">+</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				orderList: [],
				loading: false,
				refreshing: false,
				hasMore: true,
				pageNum: 1,
				pageSize: 10,
				statusIndex: 0,
				categoryIndex: 0,
				statusOptions: [
					{ name: '全部状态', value: '' },
					{ name: '待接单', value: 1 },
					{ name: '进行中', value: 2 },
					{ name: '待验收', value: 3 },
					{ name: '已完成', value: 4 },
					{ name: '已取消', value: 5 }
				],
				categoryOptions: [
					{ name: '全部分类', value: '' }
				]
			}
		},
		onLoad() {
			this.loadCategories()
			this.loadOrders()
		},
		methods: {
			async loadCategories() {
				try {
					const res = await this.$api.getCategoryList()
					if (res.code === 200) {
						const categories = res.data.map(item => ({
							name: item.name,
							value: item.id
						}))
						this.categoryOptions = [{ name: '全部分类', value: '' }, ...categories]
					}
				} catch (error) {
					uni.showToast({
						title: '加载分类失败',
						icon: 'none'
					})
				}
			},
			
			async loadOrders(refresh = false) {
				if (this.loading) return
				
				this.loading = true
				
				if (refresh) {
					this.pageNum = 1
					this.hasMore = true
				}
				
				try {
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize
					}
					
					if (this.statusOptions[this.statusIndex].value) {
						params.status = this.statusOptions[this.statusIndex].value
					}
					
					if (this.categoryOptions[this.categoryIndex].value) {
						params.categoryId = this.categoryOptions[this.categoryIndex].value
					}
					
					const res = await this.$api.getOrderList(params)
					
					if (res.code === 200) {
						const newOrders = res.data || []
						
						if (refresh) {
							this.orderList = newOrders
						} else {
							this.orderList = [...this.orderList, ...newOrders]
						}
						
						this.hasMore = newOrders.length === this.pageSize
						this.pageNum++
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					this.refreshing = false
				}
			},
			
			onRefresh() {
				this.refreshing = true
				this.loadOrders(true)
			},
			
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.loadOrders()
				}
			},
			
			onStatusChange(e) {
				this.statusIndex = e.detail.value
				this.loadOrders(true)
			},
			
			onCategoryChange(e) {
				this.categoryIndex = e.detail.value
				this.loadOrders(true)
			},
			
			goOrderDetail(id) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${id}`
				})
			},
			
			goCreateOrder() {
				uni.navigateTo({
					url: '/pages/order/create'
				})
			},
			
			showActions(order) {
				return this.canAccept(order) || this.canAssign(order) || 
					   this.canComplete(order) || this.canCancel(order)
			},
			
			canAccept(order) {
				return this.$store.getters.isTech && order.status === 1
			},
			
			canAssign(order) {
				return this.$store.getters.isDispatcher && order.status === 1
			},
			
			canComplete(order) {
				return this.$store.getters.isTech && order.status === 2 && 
					   order.techId === this.$store.getters.userInfo.id
			},
			
			canCancel(order) {
				return (this.$store.getters.isUser && order.userId === this.$store.getters.userInfo.id && order.status <= 2) ||
					   this.$store.getters.isAdmin
			},
			
			async acceptOrder(id) {
				try {
					await this.$api.acceptOrder(id)
					uni.showToast({
						title: '接单成功',
						icon: 'success'
					})
					this.loadOrders(true)
				} catch (error) {
					uni.showToast({
						title: error.message || '接单失败',
						icon: 'none'
					})
				}
			},
			
			assignOrder(id) {
				uni.navigateTo({
					url: `/pages/dispatcher/assign?orderId=${id}`
				})
			},
			
			async completeOrder(id) {
				uni.showModal({
					title: '确认完成',
					content: '确定要标记此订单为完成状态吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$api.completeOrder(id)
								uni.showToast({
									title: '操作成功',
									icon: 'success'
								})
								this.loadOrders(true)
							} catch (error) {
								uni.showToast({
									title: error.message || '操作失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			async cancelOrder(id) {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消此订单吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$api.cancelOrder(id)
								uni.showToast({
									title: '取消成功',
									icon: 'success'
								})
								this.loadOrders(true)
							} catch (error) {
								uni.showToast({
									title: error.message || '取消失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			getStatusClass(status) {
				const statusMap = {
					1: 'status-pending',
					2: 'status-processing',
					3: 'status-reviewing',
					4: 'status-completed',
					5: 'status-cancelled'
				}
				return statusMap[status] || ''
			},
			
			getStatusText(status) {
				const statusMap = {
					1: '待接单',
					2: '进行中',
					3: '待验收',
					4: '已完成',
					5: '已取消'
				}
				return statusMap[status] || '未知'
			},
			
			formatTime(time) {
				if (!time) return ''
				const date = new Date(time)
				return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-list-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: #f5f5f5;
	}
	
	.filter-bar {
		background: #fff;
		padding: 20rpx;
		display: flex;
		gap: 20rpx;
		border-bottom: 1rpx solid #eee;
		flex-wrap: wrap;
		position: sticky;
		top: 0;
		z-index: 10;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		
		.filter-item {
			flex: 1;
			min-width: 300rpx;
			padding: 20rpx;
			background: #f8f8f8;
			border-radius: 10rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			
			.arrow {
				color: #999;
				font-size: 20rpx;
			}
		}
	}
	
	.order-scroll {
		flex: 1;
		padding: 20rpx;
	}
	
	.order-item {
		background: #fff;
		border-radius: 15rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		
		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			margin-bottom: 20rpx;
			
			.order-title {
				flex: 1;
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-right: 20rpx;
				line-height: 1.4;
			}
			
			.order-status {
				font-size: 24rpx;
				padding: 6rpx 16rpx;
				border-radius: 15rpx;
				white-space: nowrap;
			}
		}
		
		.order-content {
			margin-bottom: 20rpx;
			
			.order-desc {
				font-size: 28rpx;
				color: #666;
				line-height: 1.5;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
			}
		}
		
		.order-info {
			display: flex;
			justify-content: space-between;
			align-items: flex-end;
			margin-bottom: 20rpx;
			
			.info-left {
				.budget {
					display: block;
					font-size: 36rpx;
					font-weight: bold;
					color: #FF6B6B;
					margin-bottom: 10rpx;
				}
				
				.category {
					font-size: 24rpx;
					color: #666;
					background: #f0f0f0;
					padding: 4rpx 12rpx;
					border-radius: 12rpx;
				}
			}
			
			.info-right {
				text-align: right;
				
				.user {
					display: block;
					font-size: 24rpx;
					color: #666;
					margin-bottom: 10rpx;
				}
				
				.time {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
		
		.order-actions {
			display: flex;
			gap: 20rpx;
			
			.action-btn {
				flex: 1;
				height: 60rpx;
				border: none;
				border-radius: 30rpx;
				font-size: 24rpx;
				
				&.accept {
					background: #28a745;
					color: #fff;
				}
				
				&.assign {
					background: #007bff;
					color: #fff;
				}
				
				&.complete {
					background: #17a2b8;
					color: #fff;
				}
				
				&.cancel {
					background: #dc3545;
					color: #fff;
				}
			}
		}
	}
	
	.load-more, .no-more {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.empty {
		text-align: center;
		padding: 200rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.fab {
		position: fixed;
		right: 40rpx;
		bottom: 120rpx;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50rpx;
		background: linear-gradient(45deg, #FF6B6B, #FF8E53);
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 20rpx rgba(255, 107, 107, 0.4);
		z-index: 999;
		
		.fab-icon {
			font-size: 48rpx;
			color: #fff;
			font-weight: bold;
		}
	}
</style>